from pyre.data import info
from pyre.core import types

class Menu(info.InfoDB):

    def __init__(self, menu_data):
        info.InfoDB.__init__(self, menu_data, data=lambda x: x.split('\n'),
                                              rewrites=info.parse_tile,
                                              items=info.parse_tuple)
        self.items = [item.capitalize() for item in self.data['items']]

    def run(self, terminal):
        key = '\0'
        curr = 0

        while key != '\n' and key != '\r':
            for y, line in enumerate(self.data['background']['data']):
                for x, char in enumerate(line):
                    if char in self.data['rewrites']:
                        char = self.data['rewrites'][char]
                    else:
                        char = types.ColoredChar(char)
                    terminal.buffer_char((x, y), char)

            for i, item in enumerate(self.items):
                pos = self.data['items'][item.lower()]
                color = types.Color.WHITE if i == curr else types.Color.GRAY
                for dx, char in enumerate(item):
                    char = types.ColoredChar(char, color)
                    terminal.buffer_char((pos[0] + dx, pos[1]), char)

            terminal.refresh_screen()
            key = terminal.get_key()
            delta = types.Direction.key_to_dir(key)
            if delta is not None and delta.is_orthogonal():
                curr = (curr + sum(delta)) % len(self.items)

        return self.items[curr]
